package tech.aistar.controller;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.aistar.pojo.Result;
import tech.aistar.pojo.User;
import tech.aistar.service.UserService;

/**
 * 用户控制层
 */
@RestController // = @ResponseBody + @Controller
@RequestMapping("user")
public class UserController {
    //controller层调用service
    @Autowired
    private UserService userService;

    @Autowired
    private JavaMailSender mailSender;

    @GetMapping
    public Result sendCode(String email, HttpServletRequest request){
        User user = userService.findByEmail(email);
        if(user==null)
            return new Result("404","sorry,邮箱不存在!");

        //TODO... 发送邮箱的这段代码 - 单独使用一个线程单独去处理
        //说明邮箱是存在的
        //随机数100000~999999之间随机正整数
        //java.lang.Math  static double random();//[0.0,1.0)
        int n = (int) (Math.random()*900000+100000);
        //将int类型转换成字符串类型
        String serverCode = String.valueOf(n);

        //1. 定义一个对象,封装邮件的信息
        SimpleMailMessage msg = new SimpleMailMessage();
        //邮件的发送方,此处的邮箱应该和application-dev.yml中的配置的mail下的username保持一致
        msg.setFrom("849962874@qq.com");
        //邮件的标题
        msg.setSubject("city-login验证码");
        //邮件的正文内容
        msg.setText(serverCode);
        //邮件的接收方
        msg.setTo(email);

        //TODO... 不让发送
        //真正发送
        //mailSender.send(msg);

        //TODO... 选择将serverCode放入到服务器的内存中session空间
        //①获取session对象
        HttpSession session = request.getSession();
        //存储的数据的格式也是key-value的形式
        session.setAttribute("serverCode",serverCode);

        //TODO... 验证码不要返回
        return new Result("200","发送验证码成功",serverCode);
    }

    @PostMapping
    public Result login(String email,String code,HttpServletRequest request){
        User user = userService.findByEmail(email);
        if(user==null)
            return new Result("404","sorry,邮箱不存在!");

        //根据key,从session空间获取之前生成的验证码
        HttpSession session = request.getSession();
        String serverCode = (String) session.getAttribute("serverCode");
        if(null!=serverCode && serverCode.equals(code)){
            return new Result("200","login成功!");
        }

        return new Result("500","登录失败!验证码不正确!");
    }






//    @GetMapping
//    public Result sendCode(String email){
//        System.out.println(email);
//        return new Result("200","发送验证码成功");
//    }
}
